import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import router from '../router'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    id: '',
    name: '',
    roleName: '',
    role: '',
    avatar: '',
    menuList: null
  },
  mutations: {
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ROLENAME: (state, roleName) => {
      state.roleName = roleName
    },
    SET_ROLE: (state, role) => {
      state.role = role
    },
    getList: (state, role) => {
      const async = router.options.asyncRoutes.filter(item => item.meta.roles.includes(role))
      // const publicRouter = router.options.routes.filter(item => item.children != null)
      // const publicRouter = router.options.routes
      router.addRoutes(async)
      // router.addRoutes(publicRouter)
      const filerRouter = router.options.routes.filter(item => item.children != null)
      state.menuList = [...filerRouter, ...async]
    },
    upInfo: (state, data) => {
      const { id, name, role, avatar } = data
      state.id = id
      state.name = name
      state.role = role 
      state.avatar = avatar
    }
  },
  actions: {
    getInfo({ commit }) {
      return new Promise((resolve, reject) => {
        axios.get('/user.json').then(({ data }) => {
          const { id, name, roleName, role } = data[0]
          commit('SET_ID', id)
          commit('SET_NAME', name)
          commit('SET_ROLENAME', roleName)
          commit('SET_ROLE', role)
          commit('getList', role)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    }
  },
  getters:{
    upMenu(state) {
      return state.menuList
    }
  }
})